package org.jeecg.modules.demo.officialaccountuser.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sf.json.JSONObject;
import org.jeecg.modules.demo.officialaccounttoken.service.impl.WeChatTokenService;
import org.jeecg.modules.demo.officialaccountuser.entity.OfficialAccountUser;
import org.jeecg.modules.demo.officialaccountuser.mapper.OfficialAccountUserMapper;
import org.jeecg.modules.demo.officialaccountuser.service.IOfficialAccountUserService;
import org.jeecg.modules.util.HttpUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OfficialAccountUserServiceImpl extends ServiceImpl<OfficialAccountUserMapper, OfficialAccountUser> implements IOfficialAccountUserService {
    /**
     * 获取公众号关注的用户openid
     *
     * @return
     */
    public List<String> getUserOpenId(String access_token, String nextOpenid) {
        String path = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
        path = path.replace("ACCESS_TOKEN", access_token).replace("NEXT_OPENID", nextOpenid);
        System.out.println("path:" + path);

        List<String> result = null;
        try {
            String strResp = HttpUtils.sendGet(path);
            System.out.println(strResp);

            Map map = JSON.parseObject(strResp, Map.class);
            Map tmapMap = (Map) map.get("data");

            result = (List<String>) tmapMap.get("openid");

            System.out.println(result.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 通过用户openid 获取用户信息
     *
     * @param userOpenids
     * @return
     */
    public List<OfficialAccountUser> getUserInfo(List<String> userOpenids) {
        // 1、获取access_token
        // 使用测试 wx9015ccbcccf8d2f5 02e3a6877fa5fdeadd78d0f6f3048245
        WeChatTokenService tWeChatTokenService = new WeChatTokenService();
        String tAccess_Token = tWeChatTokenService.getToken("wx42ecd92353c89e9f", "955609cb9cb5d3ee036caaed2f883277").getToken();

        // 2、封装请求数据
        List user_list = new ArrayList<Map>();
        for (int i = 0; i < userOpenids.size(); i++) {
            String openid = userOpenids.get(i);
            Map tUserMap = new HashMap<String, String>();
            tUserMap.put("openid", openid);
            tUserMap.put("lang", "zh_CN");
            user_list.add(tUserMap);
        }
        System.out.println(user_list);
        Map requestMap = new HashMap<String, List>();
        requestMap.put("user_list", user_list);
        String tUserJSON = JSONObject.fromObject(requestMap).toString();

        // 3、请求调用
        String result = getUserInfobyHttps(tAccess_Token, tUserJSON);
        System.out.println(result);

        // 4、解析返回将结果
        return parseUserInfo(result);
    }

    /**
     * 解析返回用户信息数据
     *
     * @param userInfoJSON
     * @return
     */
    private List<OfficialAccountUser> parseUserInfo(String userInfoJSON) {
        List user_info_list = new ArrayList<OfficialAccountUser>();

        Map tMapData = JSON.parseObject(userInfoJSON, Map.class);

        List<Map> tUserMaps = (List<Map>) tMapData.get("user_info_list");

        for (int i = 0; i < tUserMaps.size(); i++) {
            OfficialAccountUser officialAccountUser = new OfficialAccountUser();
            officialAccountUser.setSubscrible((Integer) tUserMaps.get(i).get("subscribe"));
            officialAccountUser.setSex((Integer) tUserMaps.get(i).get("sex"));
            officialAccountUser.setOpenId((String) tUserMaps.get(i).get("openid"));
            officialAccountUser.setNickeName((String) tUserMaps.get(i).get("nickname"));
            officialAccountUser.setLanguage((String) tUserMaps.get(i).get("language"));
            officialAccountUser.setCity((String) tUserMaps.get(i).get("city"));
            officialAccountUser.setProvince((String) tUserMaps.get(i).get("province"));
            officialAccountUser.setCountry((String) tUserMaps.get(i).get("country"));
            officialAccountUser.setHeadimgurl((String) tUserMaps.get(i).get("headimgurl"));
            officialAccountUser.setSubscribleTime((Integer) tUserMaps.get(i).get("subscribe_time"));
            officialAccountUser.setRemark((String) tUserMaps.get(i).get("remark"));
            officialAccountUser.setGroupid((Integer) tUserMaps.get(i).get("groupid"));
            save(officialAccountUser);

            user_info_list.add(officialAccountUser);
        }

        return user_info_list;
    }

    /**
     * 调用HTTPS接口，获取用户详细信息
     *
     * @param access_token
     * @param requestData
     * @return
     */
    private String getUserInfobyHttps(String access_token, String requestData) {
        // 返回报文
        String strResp = "";
        String path = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=ACCESS_TOKEN";
        path = path.replace("ACCESS_TOKEN", access_token);

        try {
            strResp = HttpUtils.sendPostJson(com.alibaba.fastjson.JSONObject.parseObject(requestData), path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strResp;
    }
}
